{% extends "base.html" %}
{% block content %}
<h2>操作日志</h2>
<div class="mb-3 d-flex align-items-center">
  <input type="text" id="log-search" placeholder="搜索操作/详情" class="form-control" style="width:200px;display:inline-block;">
  <button id="log-search-btn" class="btn btn-primary btn-sm ms-2">查询</button>
</div>
<table class="table table-bordered table-striped table-hover align-middle" style="table-layout:fixed;word-break:break-all;">
  <thead>
    <tr>
      <th style="width:60px;">ID</th>
      <th style="width:100px;">操作</th>
      <th style="width:400px;">详情</th>
      <th style="width:160px;">时间</th>
      <th style="width:100px;">任务</th>
    </tr>
  </thead>
  <tbody id="log-table"></tbody>
</table>
<div class="d-flex justify-content-end align-items-center" style="margin-top:-10px;">
  <div class="log-pagination-bar d-flex align-items-center flex-wrap gap-2">
    <span>每页</span>
    <select id="log-page-size" class="form-select form-select-sm mx-1" style="width:80px;display:inline-block;">
      <option value="10">10</option>
      <option value="20" selected>20</option>
      <option value="50">50</option>
      <option value="100">100</option>
    </select>
    <span>条，共 <span id="log-total-info">0</span> 条</span>
    <ul class="pagination flex-wrap mb-0 ms-3" id="log-pagination" style="margin-bottom:0 !important;"></ul>
  </div>
</div>
<style>
.table td, .table th { vertical-align: middle; }
.truncate-detail {
  max-width: 380px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
  vertical-align: middle;
  cursor: pointer;
}
.log-pagination-bar {
  background: #fff;
  border-radius: 8px;
  padding: 8px 16px 8px 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  font-size: 0.98rem;
}
/* 自定义气泡样式 */
.tooltip.bs-tooltip-top .tooltip-inner,
.tooltip.bs-tooltip-auto[data-popper-placement^=top] .tooltip-inner {
  background: #fff;
  color: #333;
  border-radius: 10px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
  padding: 20px 28px;
  font-size: 0.98rem;
  max-width: 800px;
  min-width: 400px;
  white-space: pre-line;
  word-break: break-all;
  text-align: left;
}
.tooltip .tooltip-arrow {
  color: #fff;
}
.tooltip-inner pre {
  min-height: 180px;
  max-height: 400px;
  overflow: auto;
  margin: 0;
  background: transparent;
  font-family: inherit;
  font-size: inherit;
  white-space: pre-wrap;
  word-break: break-all;
}
</style>
<script>
let logPage = 1, logPageSize = 20, logQuery = '';
function escapeHtml(str) {
  if (!str) return '';
  // 先替换特殊字符，再替换\n为<br>，但<pre>下无需<br>，只需保留\n
  return str.replace(/[&<>"']/g, function(tag) {
    const charsToReplace = {
      '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
    };
    return charsToReplace[tag] || tag;
  });
}
function renderDetail(detail) {
  if (!detail) return '';
  let show = detail.length > 200 ? escapeHtml(detail.slice(0,200)) + '…' : escapeHtml(detail);
  let full = escapeHtml(detail);
  if (detail.length > 200) {
    // <pre>加white-space:pre-wrap;word-break:break-all;margin:0; 保证换行
    return `<span class="truncate-detail" data-bs-toggle="tooltip" data-bs-trigger="click" data-bs-placement="top" data-bs-html="true" title="<pre style='white-space:pre-wrap;word-break:break-all;margin:0;'>${full}</pre>">${show}</span>`;
  } else {
    return `<span>${show}</span>`;
  }
}
function formatDate(dateStr) {
  if (!dateStr) return '';
  // 兼容带毫秒和不带毫秒的字符串
  let d = new Date(dateStr.replace(/-/g, '/'));
  if (isNaN(d.getTime())) return dateStr;
  let y = d.getFullYear();
  let m = (d.getMonth()+1).toString().padStart(2,'0');
  let day = d.getDate().toString().padStart(2,'0');
  let h = d.getHours().toString().padStart(2,'0');
  let min = d.getMinutes().toString().padStart(2,'0');
  let s = d.getSeconds().toString().padStart(2,'0');
  return `${y}-${m}-${day} ${h}:${min}:${s}`;
}
function loadLogs() {
  fetch(`/api/logs?q=${encodeURIComponent(logQuery)}&page=${logPage}&page_size=${logPageSize}`)
    .then(r=>r.json()).then(res=>{
      let html = res.data.map(l=>`
        <tr>
          <td>${l.id}</td>
          <td>${escapeHtml(l.action||'')}</td>
          <td>${renderDetail(l.detail||'')}</td>
          <td>${formatDate(l.created_at)}</td>
          <td>
            ${l.task_id ? `<a href="/task-detail/${l.task_id}">查看任务</a>` : ''}
          </td>
        </tr>
      `).join('');
      document.getElementById('log-table').innerHTML = html;
      // 启用tooltip，点击显示，且只允许一个tooltip同时显示
      if (window.bootstrap) {
        if (!window._logTooltipBodyBind) {
          window._currentTooltip = null;
          document.body.addEventListener('click', function(e) {
            if (window._currentTooltip && (!e.target.closest('.truncate-detail'))) {
              window._currentTooltip.hide();
              window._currentTooltip = null;
            }
          });
          window._logTooltipBodyBind = true;
        }
        document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(el=>{
          let tooltip = new bootstrap.Tooltip(el, {trigger: 'click'});
          el.addEventListener('click', function(e) {
            e.stopPropagation();
            if (window._currentTooltip && window._currentTooltip !== tooltip) {
              window._currentTooltip.hide();
            }
            window._currentTooltip = tooltip;
          });
        });
      }
      // 分页
      let totalPages = Math.max(1, Math.ceil(res.total / res.page_size));
      let pagHtml = '';
      let showPages = 7;
      let start = Math.max(1, logPage - Math.floor(showPages/2));
      let end = Math.min(totalPages, start + showPages - 1);
      if (end - start < showPages - 1) start = Math.max(1, end - showPages + 1);
      if (start > 1) pagHtml += `<li class="page-item"><a class="page-link" href="#">1</a></li>` + (start>2?'<li class="page-item disabled"><span class="page-link">…</span></li>':'');
      for(let i=start;i<=end;i++){
        pagHtml += `<li class="page-item${i===logPage?' active':''}"><a class="page-link" href="#">${i}</a></li>`;
      }
      if (end < totalPages) pagHtml += (end<totalPages-1?'<li class="page-item disabled"><span class="page-link">…</span></li>':'')+`<li class="page-item"><a class="page-link" href="#">${totalPages}</a></li>`;
      document.getElementById('log-pagination').innerHTML = pagHtml;
      document.querySelectorAll('#log-pagination .page-link').forEach((el)=>{
        if (!el.parentElement.classList.contains('disabled')) {
          el.onclick = (e)=>{
            let num = parseInt(el.textContent);
            if (!isNaN(num)) { logPage=num; loadLogs(); }
          };
        }
      });
      // 总数信息
      document.getElementById('log-total-info').textContent = res.total;
    });
}
document.getElementById('log-search-btn').onclick = ()=>{
  logQuery = document.getElementById('log-search').value.trim();
  logPage = 1;
  loadLogs();
};
document.getElementById('log-page-size').onchange = function() {
  logPageSize = parseInt(this.value);
  logPage = 1;
  loadLogs();
};
loadLogs();
</script>
{% endblock %} 